import axios from 'axios'
import { useUserStore } from '../store/modules/user'
import { storage } from '../utils/storage'
import { message, Modal } from 'ant-design-vue';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { createVNode } from 'vue';
import { useRouter } from "vue-router";

console.log(import.meta.env)
//创建axious对象
const request = axios.create({
  baseURL: 'https://www.huaicaikeyu.cn/client_api',
  withCredentials: false, // 这将适用于跨域请求
  // headers: {
  //   Accept: 'application/json',
  //   'Content-Type': 'application/json;charset=UTF-8',
  // },
  timeout: 180000 // request timeout
})

const requestBaijiahao = axios.create({
  baseURL: 'https://baijiahao.baidu.com',//'http://localhost:4000',
  withCredentials: true, // 这将适用于跨域请求
  // crossDomain: true,
  // headers: {
    // 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
    // 'Set-Cookie': '133',  // # 确保你已经定义了cookie变量
    // 'content-type': 'application/json; charset=UTF-8',
    //  'Host': 'baijiahao.baidu.com',
    // 'Origin': 'https://baijiahao.baidu.com',
    // 'User-Agent': "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36",
  // },
  timeout: 180000 // request timeout
});
// 添加请求拦截器
request.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    const { headers } = config
    // console.log('request',  method, data)
    // 若是有做鉴权token , 就给此处头部带上token
    if (storage.get('Auth-Token')) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // config.headers['X-Token'] = getToken()
      if (headers) {
         config.headers['token'] = storage.get('Auth-Token')
         config.headers["Content-Type"] = "application/json;charset=UTF-8"
      }
    }
    return config
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 添加响应拦截器
request.interceptors.response.use(
  function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.status !== 200) {
        message.error({
          content: () => res.message || '请稍后重试',
          duration: 2
        });
        if (res.status === 401) {
            // 删除用户信息
            const userStore = useUserStore()
            const router = useRouter();
            userStore.removeLogout().then(() => {
              console.log('removeLogout')
              // 跳转登录，带上接口失效所在页面的地址，登录完成后回跳使用
              router.push('/login')
            })
        }
        // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
        if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
            // to re-login
            // 'You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout',
            //  confirmButtonText: 'Re-Login',
            //  cancelButtonText: 'Cancel',
            //  type: 'warning'
            Modal.confirm({
              content: 'You have been logged out, you can cancel to stay on this page, or log in again',
              icon: createVNode(ExclamationCircleOutlined),
              onOk() {
                const userStore = useUserStore()
                return new Promise((resolve, reject) => {
                  userStore.resetToken().then(() => {
                      location.reload()
                  })
                  setTimeout(Math.random() > 0.5 ? resolve : reject, 1000);
                }).catch(() => console.log('Oops errors!'));
              },
              cancelText: 'Cancel',
              onCancel() {
                Modal.destroyAll();
              },
            });
        }
        return Promise.reject(new Error(res.message || 'Error'))
    } else {
        return res
    }
  },
  function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    console.log('err' + error) // for debug
    message.error({
      content: () => error.message || '请稍后重试',
      duration: 2
    });
    return Promise.reject(error)
  }
)


// 添加请求拦截器
requestBaijiahao.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    const { headers } = config
    // console.log('request',  method, data)
    // config.responseType = 'document'; // 设置响应类型为 document
    // 若是有做鉴权token , 就给此处头部带上token
    if (storage.get('Auth-Token')) {
      if (headers) {
        // config.headers["Access-Control-Allow-Credentials"] = "true" //允许跨域传递cookie
        // config.headers["Access-Control-Allow-Origin"] = "true" //解决跨域问题
        // const cookie = document.cookie; // 获取浏览器中的 Cookie
      }
    }
    return config
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 添加响应拦截器
requestBaijiahao.interceptors.response.use(
  function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    const res:any = response.data
    // if the custom code is not 20000, it is judged as an error.
    // 从响应头中获取token
    const token = response.headers['token']; // 例如，假设token在Authorization头中
    if(token && response.config.url == '/activity/markactivity/getuserinfo?pop_type=homepage') {
      storage.set('baijiahao-Token', token)
    }
    // console.log('token',token,response, res)
    // 可以将token存储在localStorage, sessionStorage, Vuex等地方
    if (res.errno !== 0) {
        if(res.errno == 10000015) { // 您所在网络环境异常，请完成验证
          message.error({
            content: () => '系统随机模拟人工操作，请手动发文验证一次！',
            duration: 2
          });
        }else if(res.errmsg == '账号状态异常!' || res.errno == 20040003) {// 20040003-- 用户异常 20040001-当前账号未登录res.errno == 20040001
          message.error({
            content: () => '此账号需要休息了，请重新后台更换新账号。',
            duration: 2
          });
        }else if(res.errno == 10000013){
          
        }else {
          // message.error({
          //   content: () => res.errmsg || 'Error',
          //   duration: 2
          // });
        }
        // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
        if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
            // to re-login
            // 'You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout',
            //  confirmButtonText: 'Re-Login',
            //  cancelButtonText: 'Cancel',
            //  type: 'warning'
            Modal.confirm({
              content: 'You have been logged out, you can cancel to stay on this page, or log in again',
              icon: createVNode(ExclamationCircleOutlined),
              onOk() {
                const userStore = useUserStore()
                return new Promise((resolve, reject) => {
                  userStore.resetToken().then(() => {
                      location.reload()
                  })
                  setTimeout(Math.random() > 0.5 ? resolve : reject, 1000);
                }).catch(() => console.log('Oops errors!'));
              },
              cancelText: 'Cancel',
              onCancel() {
                Modal.destroyAll();
              },
            });
        }
        return Promise.reject(new Error(res.errmsg || 'Error'))
    } else {
        return response
    }
  },
  function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    console.log('err' + error) // for debug
    message.error({
      content: () => error.message || '请稍后重试',
      duration: 2
    });
    return Promise.reject(error)
  }
)
// export default request
export {request as request,  requestBaijiahao as requestBaijiahao}
